package org.example.forum.services.impl;

import lombok.extern.slf4j.Slf4j;
import org.example.forum.common.AppResult;
import org.example.forum.common.ResultCode;
import org.example.forum.dao.UserMapper;
import org.example.forum.exception.ApplicationException;
import org.example.forum.model.User;
import org.example.forum.services.IUserService;
import org.example.forum.utils.MD5Util;
import org.example.forum.utils.StringUtil;
import org.example.forum.utils.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    /**
     * 创建一个用户
     * @param user
     */
    @Override
    public void createNormalUser(User user) {
        //1.进行非空校验
        if(user==null|| StringUtil.isEmpty(user.getUsername())||StringUtil.isEmpty(user.getNickname())
                ||StringUtil.isEmpty(user.getPassword())||StringUtil.isEmpty(user.getSalt())){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            System.out.println("user1111="+user.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //按用户名查询用户信息
        User existsUser = userMapper.selectByUserName(user.getUsername());
        //判断用户是否存在
        if(existsUser!=null){
            log.info(ResultCode.FAILED_USER_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }
        //新增用户,设置默认值
        user.setGender((byte) 2);
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        Date date=new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);
        //写入数据库
        int row = userMapper.insertSelective(user);
        if(row!=1){
            log.info(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
    }

    /**
     * 通过用户名查询
     * @param username
     * @return
     */
    @Override
    public User selectByUserName(String username) {
        if(StringUtil.isEmpty(username)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return userMapper.selectByUserName(username);
    }


    /**
     * 用户登录
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @Override
    public User login(String username, String password) {

        //1.非空校验
        if(StringUtil.isEmpty(username)||StringUtil.isEmpty(password)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //2.根据用户名查询用户信息
        User user = selectByUserName(username);

        //3.对查询结果做非空校验
        if(user==null){
            log.warn(ResultCode.FAILED_LOGIN.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //4.校验密码
        String encryptPassword = MD5Util.md5(password, user.getSalt());
        if(!encryptPassword.equalsIgnoreCase(user.getPassword())){
            log.warn(ResultCode.FAILED_LOGIN.toString()+"密码错误,username="+username);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }

        return user;
    }

    @Override
    public User selectById(Long id) {
        //非空校验
        if(id==null){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //调用dao查询数据库对象
        User user = userMapper.selectByPrimaryKey(id);
        //返回对象
        return user;
    }

    /**
     * 增加一个文章数量通过id
     * @param id
     */
    @Override
    public void addOneArticleCountById(Long id) {
        if(id==null||id<=0){
            //打印异常
            log.warn(ResultCode.FAILD_BOARD_ARTICLE_COUNT.toString());
            //抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILD_BOARD_ARTICLE_COUNT));
        }
        //查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if(user==null){
            //打印异常
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString()+"userId="+id);
            //抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //用户的发帖数量
        User updateUser=new User();
        updateUser.setId(id);
        updateUser.setArticleCount(user.getArticleCount()+1);
        //更新数据库
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row!=1){
            log.warn(ResultCode.FAILED.toString()+"受影响的行数大于1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void subOneArticleCountById(Long id) {
        if(id==null||id<=0){
            //打印异常
            log.warn(ResultCode.FAILD_BOARD_ARTICLE_COUNT.toString());
            //抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILD_BOARD_ARTICLE_COUNT));
        }
        //查询user中的信息
        User user = userMapper.selectByPrimaryKey(id);
        if(user==null){
            //打印异常
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString()+"userId="+id);
            //抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //设置要更改的参数
        User updateUser=new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount()-1);
        if(updateUser.getArticleCount()<0){
            updateUser.setArticleCount(0);
        }
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row!=1){
            log.warn(ResultCode.FAILED.toString()+"受影响的行数大于1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }

    }


    @Override
    public void modifyInfo(User user) {
        //校验用户是否存在
        if(user==null||user.getId()==null||user.getId()<0){
            //打日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //获取用户信息
        User existsUser  = userMapper.selectByPrimaryKey(user.getId());
        if(existsUser ==null){
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //可以设置一个标志位,来表示更新成功或者失败
        boolean checkAttr = false;
        //更新之前先创建一个更新对象
        User updateUser=new User();
        updateUser.setId(user.getId());

        //对用户名进行校验

        if(!StringUtil.isEmpty(user.getUsername())&&!user.getUsername().equals(existsUser.getUsername())){
            User user1 = userMapper.selectByUserName(user.getUsername());
            //判断用户是否存在,因为如果别人用了,自己就不能用
            if(user1!=null){
                //打印日志
                log.warn(ResultCode.FAILED_USER_EXISTS.toString());
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
            }
            updateUser.setUsername(user.getUsername());
            checkAttr=true;
        }
        //对昵称进行校验
        if(!StringUtil.isEmpty(user.getNickname())&&!user.getNickname().equals(existsUser.getNickname())){
            updateUser.setNickname(user.getNickname());
            checkAttr=true;
        }
        //对性别进行校验
        if(user.getGender()!=null&&user.getGender()!=existsUser.getGender()){
            updateUser.setGender(user.getGender());
            if(updateUser.getGender()>2||updateUser.getGender()<0){
                updateUser.setGender((byte) 2);
            }
            checkAttr=true;
        }
        //对邮箱进行校验

        if(!StringUtil.isEmpty(user.getEmail())&&!user.getEmail().equals(existsUser.getEmail())){
            updateUser.setEmail(user.getEmail());
            checkAttr=true;
        }
        //对电话进行校验

        if (!StringUtil.isEmpty(user.getPhoneNum())&&!user.getPhoneNum().equals(existsUser.getPhoneNum())){
            updateUser.setPhoneNum(user.getPhoneNum());
            checkAttr=true;
        }
        //对个人简介进行校验
        if(!StringUtil.isEmpty(user.getRemark())&&!user.getRemark().equals(existsUser.getRemark())){
            updateUser.setRemark(user.getRemark());
            checkAttr=true;
        }
        if(checkAttr==false){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString() + ", 受影响的行数不等于 1 .");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        if (id == null || id <= 0 || StringUtil.isEmpty(newPassword) || StringUtil.isEmpty(oldPassword)) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByPrimaryKey(id);
        if(user==null||user.getState()==1){
            // 打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //通过用户输入的旧密码和从数据库获得的盐值,获取明文
        String oldEncryptPassword  = MD5Util.md5(oldPassword, user.getSalt());
        if(!oldEncryptPassword.equalsIgnoreCase(user.getPassword())){
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //生成一个新的盐值
        String salt  = UUIDUtil.UUID_32();
        String encryptPassword  = MD5Util.md5(newPassword, salt);

        //创建更新对象
        User updateUser=new User();
        updateUser.setPassword(encryptPassword);
        updateUser.setId(user.getId());
        updateUser.setSalt(salt);
        Date date=new Date();
        updateUser.setUpdateTime(date);
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString() + ", 受影响的行数不等于 1 .");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }



}
